type 'a mult_tree = T of 'a * 'a mult_tree list;;

let rec add_string_of_tree buf (T (c, sub)) =
  Buffer.add_char buf c;
  List.iter (add_string_of_tree buf) sub;
  Buffer.add_char buf '^';; (* 所有子树处理完毕输出 "^" *)

let string_of_tree t =
  let buf = Buffer.create 128 in
  add_string_of_tree buf t;
  Buffer.contents buf;;

let tree_of_string s =
  let rec parse_node chars =
    match chars with
    | [] -> failwith "Unexpected end of input (expecting node)"
    | c :: rest ->
        let (children, rest') = parse_children rest in
        (T (c, children), rest')
  and parse_children chars =
    match chars with
    | [] -> failwith "Unexpected end of input (expecting ^)"
    | '^' :: rest -> ([], rest)
    | _ ->
        let (child, rest') = parse_node chars in
        let (siblings, rest'') = parse_children rest' in
        (child :: siblings, rest'')
  in
  let (tree, remaining) = parse_node (List.of_seq (String.to_seq s)) in
  match remaining with
  | [] -> tree
  | _ -> failwith "Extra input after tree";;

let t = T('a', [T('f',[T('g',[])]); T('c',[]);
          T('b',[T('d',[]); T('e',[])])]);;

string_of_tree t;;

tree_of_string "afg^^c^bd^e^^^";;